<template>
  <div class="server-detail-page">
    <div class="page-header">
      <el-page-header @back="goBack">
        <template #content>服务器详情</template>
      </el-page-header>
    </div>
    <ServerDetail v-if="server" :server="server" @edit="handleEdit" @delete="handleDelete" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ServerInfo } from '@/api/types'
import { assetService } from '@/api/assetService'
import ServerDetail from '@/components/asset/ServerDetail.vue'

const route = useRoute()
const router = useRouter()
const server = ref<ServerInfo>()

const fetchServerDetail = async () => {
  try {
    const serverId = parseInt(route.params.id as string)
    const data = await assetService.getServerById(serverId)
    server.value = data
  } catch (err) {
    console.error('获取服务器详情失败:', err)
    ElMessage.error('获取服务器详情失败')
  }
}

const goBack = () => {
  router.back()
}

const handleEdit = (serverData: ServerInfo) => {
  console.log('Edit server:', serverData)
}

const handleDelete = async (serverData: ServerInfo) => {
  try {
    await ElMessageBox.confirm(`确认删除服务器 ${serverData.hostname}？`, '提示', {
      type: 'warning',
    })
    await assetService.deleteServer(serverData.id)
    ElMessage.success('删除成功')
    router.back()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务器失败:', error)
      ElMessage.error('删除服务器失败')
    }
  }
}

onMounted(() => {
  fetchServerDetail()
})
</script>

<style scoped lang="scss">
.server-detail-page {
  .page-header {
    margin-bottom: 24px;
  }
}
</style>
